//
//  CALoginViewController.m
//  LNH
//
//  Created by twentylx on 2018/2/4.
//  Copyright © 2018年 twentylx. All rights reserved.
//

#import "CALoginViewController.h"
#import "CALoginView.h"
#import "CALoginBottomView.h"

#import "CAGetVerifyCodeApi.h"
#import "CALoginApi.h"
#import "CAScanerViewController.h"

@interface CALoginViewController () <CAScanerViewControllerDelegate>{
    NSString *_verifyCode;
    NSInteger timeSecond;
}

@property (nonatomic, strong) CALoginView *loginView;
@property (nonatomic, strong) CALoginBottomView *bottomView;

@end

@implementation CALoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = RGBCOLOR(241, 241, 241);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/// 初始化数据
- (void)lm_initialDefaultsForController {
    
}

/// 绑定 vm
- (void)lm_bindViewModelForController {
    
}

/// 创建视图
- (void)lm_createViewForController {
    [self.view setNeedsUpdateConstraints];
    
    [self.view addSubview:self.loginView];
    [self.view addSubview:self.bottomView];
}

/// 配置导航栏
- (void)lm_configNavigationForController {
    self.navigationItem.title = @"绑定手机";
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

#pragma mark layout
- (void)updateViewConstraints {
    [super updateViewConstraints];
    
    [_loginView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(20);
        make.height.mas_offset(135);
    }];
    
    [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.view);
        make.top.equalTo(self.loginView.mas_bottom);
        make.bottom.equalTo(self.view);
    }];
}

#pragma mark get & set
- (CALoginView *)loginView {
    if (!_loginView) {
        _loginView = [CALoginView new];
        [_loginView.msgButton addTarget:self action:@selector(sendCodeAction) forControlEvents:UIControlEventTouchDown];
        [[_loginView.scanButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            CAScanerViewController *scanerVC = [CAScanerViewController new];
            scanerVC.delegate = self;
            [self.navigationController pushViewController:scanerVC animated:YES];
        }];
    }
    return _loginView;
}

- (CALoginBottomView *)bottomView {
    if (!_bottomView) {
        _bottomView = [CALoginBottomView new];
        [_bottomView.loginButton addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _bottomView;
}

#pragma mark event response
-(void) countdownAction:(NSTimer *) timer {
    if (timeSecond == 0) {
        [self.loginView.msgButton setBackgroundColor:RGBCOLOR(255, 61, 0)];
        [self.loginView.msgButton setTitle:@"再次获取验证码" forState:UIControlStateNormal];
        [self.loginView.msgButton setUserInteractionEnabled:YES];
        [timer invalidate];
        [self.loginView.verifyCodeTextField becomeFirstResponder];
    } else {
        timeSecond--;
        [self.loginView.msgButton setTitle:[NSString stringWithFormat:@"%lds", timeSecond] forState:UIControlStateNormal];
        [self.loginView.msgButton setBackgroundColor:RGBCOLOR(195, 195, 195)];
        [self.loginView.msgButton setUserInteractionEnabled:NO];
    }
}

- (void) sendCodeAction {
    if (self.loginView.phoneTextField.text.length != 11) {
        [SVProgressHUD lm_displayErrorWithStatus:@"请输入正确的手机号"];
        return;
    }
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    CAGetVerifyCodeApi *getVerifyCodeApi = [[CAGetVerifyCodeApi alloc] initWithPhone:self.loginView.phoneTextField.text];
    [getVerifyCodeApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSLog(@"验证码%@",request.responseJSONObject);
        CAGetVerifyCodeApi *api = (CAGetVerifyCodeApi *)request;
        if (api.done) {
            _verifyCode =[NSString stringWithFormat:@"%@",api.responseJSONObject[@"result"]];
            timeSecond = 60;
            [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countdownAction:) userInfo:nil repeats:YES];
            
            [SVProgressHUD lm_dispalyInfoWithStatus:[NSString stringWithFormat:@"测试验证码为：%@", _verifyCode]];
            [_loginView.verifyCodeTextField becomeFirstResponder];
            
        }else{
            [SVProgressHUD lm_displayErrorWithStatus:api.errorMsg];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [SVProgressHUD lm_displayErrorWithStatus:@"请求出错"];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

- (void) loginAction {
    NSString *phone = _loginView.phoneTextField.text;
    NSString *verify = _loginView.verifyCodeTextField.text;
    NSString *tjm = _loginView.tjmTextField.text;
    CALoginApi *loginApi = [[CALoginApi alloc] initWithPhone:phone VerifyCode:verify TJM:tjm];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [loginApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        CALoginApi *api = (CALoginApi *) request;
        if (api.done) {
            NSLog(@"%@", api.responseObject);
            [GVUserDefaults standardUserDefaults].token = api.responseObject[@"result"][@"token"];
            [GVUserDefaults standardUserDefaults].level = api.responseObject[@"result"][@"level"];
            [GVUserDefaults standardUserDefaults].levelName = api.responseObject[@"result"][@"levelName"];
            [GVUserDefaults standardUserDefaults].mobile = api.responseObject[@"result"][@"mobile"];
            [GVUserDefaults standardUserDefaults].inviteCode = api.responseObject[@"result"][@"invite_code"];
            [GVUserDefaults standardUserDefaults].portrait = api.responseObject[@"result"][@"portrait"];
            [GVUserDefaults standardUserDefaults].parent = api.responseObject[@"result"][@"parent"];
            [GVUserDefaults standardUserDefaults].parentName = api.responseObject[@"result"][@"parent_name"];
            [GVUserDefaults standardUserDefaults].money = api.responseObject[@"result"][@"money"];
            [GVUserDefaults standardUserDefaults].cidName = api.responseObject[@"result"][@"cid_name"];
            [GVUserDefaults standardUserDefaults].cidAddress = api.responseObject[@"result"][@"cid_address"];
            [GVUserDefaults standardUserDefaults].cid = api.responseObject[@"result"][@"cid"];
            [GVUserDefaults standardUserDefaults].wechat = api.responseObject[@"result"][@"wechat"];
            [GVUserDefaults standardUserDefaults].isLogin = YES;
            
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [SVProgressHUD lm_displayErrorWithStatus:api.errorMsg];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
         [SVProgressHUD lm_displayErrorWithStatus:@"请求出错"];
    }];
}

#pragma mark CAScanerViewControllerDelegate
-(void) scanWithQRCode:(NSString *) qrCode {
    self.loginView.tjmTextField.text = qrCode;
}

@end
